<?php

require_once APP_DIR . '/models/Page.php';
require_once APP_DIR . '/models/Revision.php';
require_once APP_DIR . '/models/Content.php';
require_once APP_DIR . '/models/User.php';

class Sites
{
	/**
	 * An gateway to retrieve instances of the Page active record object.
	 *
	 * @var Zend_Db_ActiveRecord_Gateway
	 */
	protected $pages;
	
	/**
	 * An gateway to retrieve instances of the Revision active record object.
	 *
	 * @var Zend_Db_ActiveRecord_Gateway
	 */
	protected $revisions;
	
	/**
	 * An gateway to retrieve instances of the Content active record object.
	 *
	 * @var Zend_Db_ActiveRecord_Gateway
	 */
	protected $contents;
	
	
	public function __construct()
	{
		$this->pages = new Zend_Db_ActiveRecord_Gateway('Page');
		$this->revisions = new Zend_Db_ActiveRecord_Gateway('Revision');
		$this->contents = new Zend_Db_ActiveRecord_Gateway('Content');
	}
	
	
	public function loadPages() {
		$select = $this->pages->select();
		$select->order('path');
		return $this->pages->fetchAll();
	}
	
	
	public function createPage($page)
	{
		$page = $this->pages->create($page);
		$revision = new Revision();
		$content = new Content();
		$content->field = 'title';
		$content->value = $page->title;
		$revision->contents[] = $content;
		$page->revisions[] = $revision;
		$page->saveRevisions();
		return $page;
	}
	
	public function savePage($page)
	{
		$page = new Page($page);
		$page->save();
		return $page;
	}
	
	public function deletePage($pageId)
	{
		$this->pages->delete($pageId);
	}
	
	public function getRevisions($pageId)
	{
		$select = $this->revisions->select();
		$select->where('page_id', $pageId)->order('created DESC');
		return $this->revisions->fetchAll($select);
	}
	
	public function saveRevision($pageId, $revision)
	{
		$revision = new Revision($revision);
		$revision->pageId = $pageId;
		$revision->save();
		return $revision;
	}
	
	public function deleteRevision($revisionId)
	{
		$this->revisions->delete($revisionId);
	}
	
	public function getContents($revisionId)
	{
		$select = $this->contents->select();
		$select->where('revision_id', $revisionId)->order('created DESC');
		return $this->contents->fetchAll($select);
	}
	
	public function saveContent($revisionId, $content)
	{
		$content = new Content($content);
		$content->revisionId = $revisionId;
	}
	
}
